package com.similarworld.service;

import java.util.Date;
import java.util.List;

import com.similarworld.dao.AbstractDAO;
import com.similarworld.model.AbstractModel;
import com.similarworld.util.SecurityUtils;

public abstract class AbstractService <T extends AbstractModel> {

	protected abstract AbstractDAO<T> getDAO();
	
	public T get( final Long id ){
		return getDAO().get(id);
	}

	public List< T > getAll(){
		return getDAO().getAll();
	}

	public void save( final T entity ){
		if(!entity.isCreateUserManually())
			entity.setCreateUser(SecurityUtils.getLoginUser());
		entity.setCreateDate(new Date());
		getDAO().save(entity);
	}
	
	public void saveAnyModel( final AbstractModel entity ){
		if(!entity.isCreateUserManually())
			entity.setCreateUser(SecurityUtils.getLoginUser());
		entity.setCreateDate(new Date());
		getDAO().saveAnyModel(entity);
	}
	
	public AbstractModel mergeAnyModel( final AbstractModel entity ){
		if(entity.getId() == null) {
			saveAnyModel(entity);
		} else {
			return updateAnyModel(entity);
		}
		return entity;
	}

	public T update( final T entity ){
		entity.setUpdateUser(SecurityUtils.getLoginUser());
		entity.setUpdateDate(new Date());
		return getDAO().update(entity);
	}
	
	public AbstractModel updateAnyModel( final AbstractModel entity ){
		entity.setUpdateUser(SecurityUtils.getLoginUser());
		entity.setUpdateDate(new Date());
		return getDAO().mergeAnyModel(entity);
	}

	public void delete( final T entity ){
		getDAO().delete(entity);
	}

	public int deleteById( Long id ){
		return getDAO().deleteById(id);
	}
	
}
